import React, { PureComponent } from "react";
import { NativeModules, Platform, Alert, Linking, NativeEventEmitter } from "react-native";
import { WhiteSpace } from "@ant-design/react-native";
import { barcodeReceived } from "utils";

const { RNReload, RNQRCode, iOSModule } = NativeModules;

export default class CustomeQR extends PureComponent {
  componentDidMount() {
    if (this.finishedScan) this.finishedScan.remove();
    if (Platform.OS === "ios"){
      const calendarManagerEmitter = new NativeEventEmitter(
        NativeModules.iOSModule
      );
      this.finishedSubscription = calendarManagerEmitter.addListener(
        "ScanCallback",
        data => {
          this.barcodeReceived(data)
        }
      )
    }
  }

  openQR = lacale => {
    if(Platform.OS === "android"){
      RNQRCode.openQR(lacale, msg => {
        this.barcodeReceived(msg);
      });
    }else{
      iOSModule.openQR(lacale)
    }
  };

  barcodeReceived = e => {
    if (e) {
      // this.setState({ loading: true });
      const result = e.data;
      console.log("result:", result);
      const { navigation } = this.props;
      // /(http|https):\/\/([\w.]+\/?)\S*/
      const reg = new RegExp(/(http|https):\/\/([\w.]+\/?)\S*/);
      const reg2 = new RegExp(/(rnapp):\/\/([\w.]+\/?)\S*/);
      if (reg.test(result)) {
        // navigation.navigate("webviewurl", { url: result });
        // openBrowser
        this.localUpdateVersion(result);
      } else if (reg2.test(result)) {
        // rnapp://home/id?
        const newText = result.replace(new RegExp(["rnapp://"], "ig"), "");
        // const keyArr = newText.split("/").filter(k => k);
        navigation.navigate(newText);
      } else {
        navigation.navigate("SearchDetail", { content: result });
      }
    } else {
      // this.setState({ loading: false });

      Alert.alert(
        `${global.lang.home.notice}`,
        `${global.lang.home.scanerror}`,
        [
          {
            text: `${global.lang.home.confirm}`,
            onPress: () => {},
          },
        ],
        { cancelable: false }
      );
    }
  };

  localUpdateVersion = url => {
    if (
      Platform.OS === "android" &&
      typeof RNReload.openBrowser === "function"
    ) {
      RNReload.openBrowser(url);
    } else if (Platform.OS === "ios") {
      Linking.openURL(url);
    }
  };

  render() {
    return <WhiteSpace />;
  }
}
